package dao;

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import models.Usuario;


public class UsuarioDAO {
	
	
	public static Usuario findById(int id){
		Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction tr = null;
		Usuario u = null;
		try {
			tr = session.beginTransaction();
			Query q= session.createQuery("from Usuario u WHERE u.id = :id");
			q.setParameter("id", id);
			u = (Usuario) q.uniqueResult();
			tr.commit();
			
		}catch (HibernateException e) {
			tr.rollback();
			e.printStackTrace();
		}finally{
			session.close();
		}
		return u;
	}
	
	public static Usuario findByLogin(String user, String password){
		Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction tr = null;
		Usuario u = null;
		try {
			tr = session.beginTransaction();
			Query q = session.createQuery("FROM Usuario u WHERE u.user = :user AND u.password = :password");
			q.setParameter("user", user);
			q.setParameter("password", password);
			u = (Usuario) q.uniqueResult();
			tr.commit();
		}catch (HibernateException e) {
			tr.rollback();
			e.printStackTrace();
		}finally{
			session.close();
		}
		return u;
	}
	
	@SuppressWarnings("unchecked")
	public static List<Usuario> getListUsers(){
		Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction tr = null;
		List<Usuario> u = null;
		try {
			tr = session.beginTransaction();
			//Models Usuario es case sensityve en java, en sql no lo es
			Query q = session.createQuery("FROM Usuario u WHERE NOT u.cargo = :cargo");
			q.setParameter("cargo", "Administrador");
			u = (List<Usuario>) q.list();
			tr.commit();
		}catch (HibernateException e) {
			tr.rollback();
			e.printStackTrace();
		}finally{
			session.close();
		}
		return u;
	}
	
	public static void persistUser(Usuario user){
		Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction tr = null;
		try{
			tr = session.beginTransaction();
			session.persist(user);
			tr.commit();
		}catch(HibernateException e){
			tr.rollback();
			e.printStackTrace();
		}finally{
			session.close();
		}
	}
	
	public static void updateUser(Usuario user){
		Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction tr =null;
		try{
			tr = session.beginTransaction();
			session.update(user);
			tr.commit();
		}catch(HibernateException e){
			tr.rollback();
			e.printStackTrace();
		}finally{
			session.close();
		}
	}
}
